package com.dgsrz.demo.primitive;

import javax.microedition.khronos.opengles.GL10;
import java.nio.ByteBuffer;
import java.nio.ByteOrder;
import java.nio.FloatBuffer;

/**
 * Created by dgsrz on 15/7/2.
 */
public class TexturedCircle extends PrimitiveBase {

    private final int PRIM_VERTEX_NUM = 34;

    private final float PRIM_VERTEX[];
    private final float PRIM_TEX_COORDS[];

    private FloatBuffer mVertexBuffer;
    private FloatBuffer mTexBuffer;

    public TexturedCircle(final GL10 gl) {
        super(gl);

        PRIM_VERTEX = new float[PRIM_VERTEX_NUM * 3];
        PRIM_VERTEX[0] = 0f;  // X axis
        PRIM_VERTEX[1] = 0f;  // Y axis
        PRIM_VERTEX[2] = 0f;  // Z axis
        for (int i = 1; i < PRIM_VERTEX_NUM; i++) {
            double angle = (i - 1) * Math.PI / 32f;
            PRIM_VERTEX[i * 3] = 32f * (float)(Math.sin(angle));
            PRIM_VERTEX[i * 3 + 1] = -32f * (float)(Math.cos(angle));
            PRIM_VERTEX[i * 3 + 2] = -256;
        }

        PRIM_TEX_COORDS = new float[PRIM_VERTEX_NUM * 2];
        PRIM_TEX_COORDS[0] = 1f;  // X axis
        PRIM_TEX_COORDS[1] = 1f;  // Y axis
        for (int i = 1; i < PRIM_VERTEX_NUM; i++) {
            PRIM_TEX_COORDS[i * 2] = 0f;
            PRIM_TEX_COORDS[i * 2 + 1] = 0f;
        }

        ByteBuffer vbb = ByteBuffer.allocateDirect(PRIM_VERTEX_NUM * 3 * 4);
        vbb.order(ByteOrder.nativeOrder());
        mVertexBuffer = vbb.asFloatBuffer();
        mVertexBuffer.put(PRIM_VERTEX);
        mVertexBuffer.position(0);

        ByteBuffer tbb = ByteBuffer.allocateDirect(PRIM_VERTEX_NUM * 2 * 4);
        tbb.order(ByteOrder.nativeOrder());
        mTexBuffer = tbb.asFloatBuffer();
        mTexBuffer.put(PRIM_TEX_COORDS);
        mTexBuffer.position(0);
    }

    @Override
    public void drawPrimitives() {
        final GL10 gl = getGLStateManager();

        gl.glFrontFace(GL10.GL_CCW);
        gl.glVertexPointer(3, GL10.GL_FLOAT, 0, mVertexBuffer);
        gl.glEnable(GL10.GL_TEXTURE_2D);
        gl.glTexCoordPointer(2, GL10.GL_FLOAT, 0, mTexBuffer);
        gl.glDrawArrays(GL10.GL_TRIANGLE_FAN, 0, PRIM_VERTEX_NUM);
    }
}
